/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao.impl.jpa;

import java.sql.SQLException;

import javax.persistence.*;

import org.eclipse.persistence.exceptions.DatabaseException;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import dao.IBasePersistence;
import domain.Persoon;
import domain.Planning;
import domain.Reis;

public abstract class BasePersistence implements IBasePersistence {
    protected EntityManagerFactory emf;
    protected EntityManager em;

    protected void open() {
        emf = Persistence.createEntityManagerFactory("Shoestring");
        em = emf.createEntityManager();
    }

    protected void close() {
        em.close();
        emf.close();
    }
    
    @Override
	public void save(Object object) throws SQLException {
    	open();
    	try {
        	em.getTransaction().begin();
	    	em.persist(em.merge(object));
	    	em.getTransaction().commit();
    	} catch (Throwable e) {
			throw new SQLException(e.getMessage());
		} finally {    	
			close();
		}
    }
    
    @Override
	public void delete(Object object) throws SQLException {
    	open();
    	try {
        	em.getTransaction().begin();
	    	em.remove(em.merge(object));
	    	em.getTransaction().commit();
    	} catch (Throwable e) {
    		if(e.getCause() instanceof DatabaseException &&
    				e.getCause().getCause() instanceof MySQLIntegrityConstraintViolationException) {
    			if(object instanceof Reis) {
        			throw new SQLException("Deze reis bevat geplande items en kan niet worden verwijderd");
    			}
    			else if(object instanceof Planning) {
        			throw new SQLException("Er zijn al reserveringen geboekt, dit geplande item kan niet worden verwijderd");
    			}
    			else if(object instanceof Persoon) {
           			throw new SQLException("Deze persoon is al gekoppeld aan een reis en kan niet worden verwijderd");
    			}
    		}
			throw new SQLException(e.getCause().getMessage());
		} finally {    	
			close();
		}
   }
}
